class_name EnemyBase
extends CharacterBody2D

# 基本属性
var max_health: float = 100.0
var current_health: float = 100.0
var move_speed: float = 100.0
var attack_damage: float = 10.0
var is_dead: bool = false
var is_hurt: bool = false
var state: String = "idle"

# 组件引用
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var health_bar = $HealthBar

# 获取重力值
func get_gravity_value() -> Vector2:
	return Vector2(0, ProjectSettings.get_setting("physics/2d/default_gravity"))

# 基本的物理处理
func _physics_process(delta: float) -> void:
	# 如果已经死亡，不处理物理
	if is_dead:
		return
		
	# 添加重力
	if not is_on_floor():
		velocity.y += get_gravity_value().y * delta
	
	move_and_slide()

# 受到伤害
func take_damage(amount: float, source_position: Vector2 = Vector2.ZERO, is_quick_slash: bool = false) -> void:
	if is_dead or is_hurt:
		return
		
	current_health -= amount
	current_health = max(0, current_health)
	
	# 更新血条
	if health_bar:
		health_bar.set_health(current_health, max_health)
	
	# 计算击退方向
	var dir = (global_position - source_position).normalized()
	
	# 根据攻击类型应用不同的击退
	if is_quick_slash:
		# 疾风斩带来更强的击退效果
		velocity.x = dir.x * 300.0  # 更强的水平击退
		velocity.y = -100.0  # 轻微向上击退
		
		# 疾风斩时敌人不会进入受伤状态，玩家可以直接穿过
		# 应用短暂闪烁效果表示命中
		var tween = create_tween()
		tween.tween_property(self, "modulate", Color(2.0, 1.5, 1.5, 0.7), 0.1)
		tween.tween_property(self, "modulate", Color(1, 1, 1, 1), 0.1)
	else:
		# 普通攻击的击退
		velocity.x = dir.x * 150.0
		velocity.y = -50.0
		
		# 受伤状态
		is_hurt = true
		animated_sprite.play("hurt")
		
		# 受伤后短暂无敌时间
		await get_tree().create_timer(0.5).timeout
		is_hurt = false
	
	# 检查是否死亡
	if current_health <= 0:
		die()

# 死亡处理
func die() -> void:
	is_dead = true
	animated_sprite.play("death")
	# 禁用碰撞
	$CollisionShape2D.set_deferred("disabled", true)
	
	# 死亡后移除
	await get_tree().create_timer(1.0).timeout
	queue_free()

# 初始化
func _ready() -> void:
	# 确保添加到enemy组
	add_to_group("enemy")
	print("敌人已添加到enemy组")
	
	# 初始化血条
	if health_bar:
		health_bar.set_health(current_health, max_health)
